
package com.capgemini.fs.presentation.role.web.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.capgemini.fs.app.ekms.common.Constants;
import com.capgemini.fs.app.ekms.model.Functionality;
import com.capgemini.fs.app.ekms.model.Role;
import com.capgemini.fs.app.ekms.service.FunctionalityService;
import com.capgemini.fs.app.ekms.service.RoleService;

import com.capgemini.fs.presentation.role.web.form.CreateRoleForm;

/**
 * CreateRoleAction Class
 * 
 * 
 * @version 1.0
 * @author Jack
 * 
 */
public class CreateRoleAction extends DispatchAction {
	private FunctionalityService functionalityService;

	private RoleService roleService;

	public RoleService getRoleService() {
		return roleService;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	public FunctionalityService getFunctionalityService() {
		return functionalityService;
	}

	public void setFunctionalityService(
			FunctionalityService functionalityService) {
		this.functionalityService = functionalityService;
	}

	/**
	 * Load role information when action type is load
	 * 
	 * @throws Exception
	 */
	public ActionForward load(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			/* Get all functionalities */
			List<Functionality> functionalityList = functionalityService
					.getAllFunctionalities();
			
			/*Get functionality category*/
			List<String> categoryList = functionalityService
					.getAllFunctionalityCategories();

			CreateRoleForm createRoleForm = new CreateRoleForm();
			
			createRoleForm.setCategoryList(categoryList);
			createRoleForm.setFunctionalityList(functionalityList);

			/*Return createRoleForm to page*/
			request.setAttribute("createRoleForm", createRoleForm);

			return mapping.findForward("succ");
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	/**
	 * Create role information when action type is create
	 * 
	 * @throws Exception
	 */
	public ActionForward create(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			/*Get session from request*/
			HttpSession session = request.getSession();
			
			/* Insert Role */
			CreateRoleForm roleForm = (CreateRoleForm) form;
			Role role = new Role();

			role.setName(roleForm.getRole_name());

			role.setCreator(session.getAttribute("username").toString());
			role.setLastModifier(session.getAttribute("username").toString());
			role.setCreateDate(new Date());
			role.setLastUpdateDate(new Date());
			
			/*Set role status*/
			if (roleForm.getRoleActive().equals("Yes")) {	//Active role
				role.setStatus(Constants.ROLE_STATUS_ACTIVE);
			} else if (roleForm.getRoleActive().equals("No")) {		//Inactive role
				role.setStatus(Constants.ROLE_STATUS_INACTIVE);
			}
			/* Construct FunctionalityList */
			Set<Functionality> functionalityListForInsert = new HashSet<Functionality>();
			String[] selectedFunctionList = roleForm.getFunctionCheckBox();
			if (selectedFunctionList != null) {
				for (int i = 0; i < selectedFunctionList.length; i++) {
					Functionality functionality = functionalityService
							.getFunctionalityByFunctionalityCode(selectedFunctionList[i]);
					functionalityListForInsert.add(functionality);
				}
			}
			role.setFunctionalities(functionalityListForInsert);

			/*Create role*/
			roleService.createRole(role);

			/* Get FunctionalityList */
			List<Functionality> functionalityList = functionalityService
					.getAllFunctionalities();
			List<String> categoryList = functionalityService
					.getAllFunctionalityCategories();

			CreateRoleForm createRoleForm = new CreateRoleForm();
			createRoleForm.setCategoryList(categoryList);
			createRoleForm.setFunctionalityList(functionalityList);

			/*Return createRoleForm to page*/
			request.setAttribute("createRoleForm", createRoleForm);
			
			/*Set success information to page*/
			request.setAttribute("Success", "Created Successfully!");

			return mapping.findForward("succ");
		} catch (Exception e) {
			e.printStackTrace();
			return mapping.findForward("failed");
		}
	}

	/**
	 * Check Role Name
	 * 
	 * @throws Exception
	 */
	public ActionForward checkRoleName(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		/*Initialize the JSON object*/
		String jsonString = readJSONRequest(request);
		JSONObject jot = JSONObject.fromObject(jsonString);
		Role role = serializeRole(jot);
		String roleNameExist;

		if (roleService.getRoleByName(role.getName()) != null) {	//role name exists
			roleNameExist = "Yes";
		} else {	//role name does not exist
			roleNameExist = "No";
		}

		/*Return JSON object to page*/
		try {
			PrintWriter out = response.getWriter();
			JSONObject jsonObject = new JSONObject();
			JSONObject jso = new JSONObject();
			jso.put("roleNameExist", roleNameExist);
			jsonObject.put("notice", "Modified Successfully!");
			jsonObject.put("role", jso);
			out.print(jsonObject);
			out.flush();
			out.close();
			return null;
		} catch (Exception exc) {
			exc.printStackTrace();
			throw exc;
		}
	}

	/**
	 * Read JSON By Request
	 * 
	 * @throws IOException
	 */
	private String readJSONRequest(HttpServletRequest request)
			throws IOException {
		StringBuffer sb = new StringBuffer();
		String line;
		try {
			BufferedReader reader = request.getReader();
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		}
		return sb.toString();
	}

	/**
	 * serialize a Group from JSONObject
	 * 
	 * @throws IOException
	 */
	public Role serializeRole(JSONObject jo) {
		Role role = new Role();

		role.setName(jo.getString("roleName"));
		return role;
	}
}
